package float
{
   import flash.display.DisplayObjectContainer;
   import flash.display.MovieClip;
   
   import jp.progression.commands.display.AddChild;
   import jp.progression.commands.display.AddChildAt;
   import jp.progression.commands.display.RemoveChild;
   import jp.progression.events.ProcessEvent;
   import jp.progression.scenes.SceneObject;
   
   /**
    * @author  cjboy1984@gmail.com
    */
   public class FloatScene extends SceneObject
   {
      // a const name
      public static const NAME:String = 'float';
      
      // a class inherits from MovieClip.
      private var cast:MovieClip;
      private var myContainer:DisplayObjectContainer;
      
      // layer index
      private var layerIndex:int;
      
      public function FloatScene($container:DisplayObjectContainer, $cast:MovieClip, layer_index:int = -1)
      {
         super(NAME);
         
         cast = $cast;
         myContainer = $container;
         
         // index
         layerIndex = layer_index;
      }
      
      // ################### protected ##################
      
      override protected function atSceneLoad():void
      {
         // check container: if it is null, then container will be stage.
         if (!myContainer)
         {
            myContainer = stage;
         }
         
         // check given lyaerIndex
         if (layerIndex < 0)
         {
            addCommand(
               new AddChild(myContainer, cast)
            );
         }
         else
         {
            // check layerIndex
            if (layerIndex >= myContainer.numChildren - 1)
            {
               layerIndex = myContainer.numChildren - 1;
            }
            
            addCommand(
               new AddChildAt(myContainer, cast, layerIndex)
            );
         }
      }
      
      override protected function atSceneUnload():void
      {
         // Remove this scene when arriving destinate scene.
         // Bug - 如果移除此場景的話會讓上下一步出錯！但不移除又會導至scene結構過於複雜
         manager.addEventListener(ProcessEvent.PROCESS_COMPLETE, onSceneProcessEnd);
         
         addCommand(
            new RemoveChild(myContainer, cast)
         );
      }
      
      override protected function atSceneInit():void {}
      override protected function atSceneGoto():void {}
      override protected function atSceneAscend():void {}
      override protected function atSceneDescend():void {}
      
      // #################### private ###################
      
      private function onSceneProcessEnd(e:ProcessEvent):void
      {
         // remove the listener.
         manager.removeEventListener(ProcessEvent.PROCESS_COMPLETE, onSceneProcessEnd);
         // It make manager no longer available.
         parent.removeScene(this);
      }
      
      // --------------------- LINE ---------------------
      
   }
   
}
